#include "socket_basic.hpp"

class UDP_Client : public socket_basic
{
public:
    UDP_Client(uint16_t port, std::string ip_addr) : socket_basic(port, inet_addr(ip_addr.c_str()))
    {
    }
    void Start()
    {
        std::string message;
        while (true)
        {
            std::cout << "Please Enter##";
            std::getline(std::cin, message);
            ssize_t n = sendto(_sockfd, message.c_str(), strlen(message.c_str()), 0, reinterpret_cast<const sockaddr *>(&_addr), sizeof(_addr));
            if (n < 0)
            {
                _log(ERROR, __LINE__, __FILE__, "client sendto error!\n");
                break;
            }

            // 接收服务端
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            char buffer[1024];
            uint32_t peer_len = sizeof(peer);
            n = recvfrom(_sockfd, static_cast<void *>(buffer), sizeof(buffer), 0, reinterpret_cast<sockaddr *>(&peer), &peer_len);
            if(n == -1)
            {
                _log(ERROR,__LINE__,__FILE__,"client recvfrom error!\n");
            }
            std::cout << "server response##" << buffer << std::endl;
        }
    }
};
void Usage(std::string str)
{
    printf("Usage:\n     %s local_ip local_port\n", str.c_str());
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }
    std::string ip_addr = argv[1];
    uint16_t port = std::stoi(argv[2]);
    UDP_Client client(port, ip_addr);
    client.Start();
    return 0;
}